//
//  FQDDetailToolBar.m
//  FakeQDaily
//
//  Created by mewxiv on 8/20/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDDetailToolBar.h"
#import "FQDDetailToolBarButton.h"

#import "Masonry.h"

static CGSize const ToolBarButtonSize = (CGSize){50.0f, 50.0f};

@interface FQDDetailToolBar ()

@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) FQDDetailToolBarButton *commentButton;

@end

@implementation FQDDetailToolBar


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareUI];
        [self prepareConstraints];
    }
    return self;
}

- (instancetype)initWithBarButtons:(NSArray *)barButtons
{
    self = [self initWithFrame:CGRectZero];
    if (self) {
        _barButtons = barButtons;
        [self configureBarButtons];
    }
    return self;
}

- (void)prepareUI
{
    UIImage *bgImage = [UIImage imageNamed:@"toolbarBg"];
    bgImage = [bgImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 32.0f, 0, 32.0f)
                                      resizingMode:UIImageResizingModeStretch];
    _bgImageView = [[UIImageView alloc] initWithFrame:self.bounds];
    _bgImageView.contentMode = UIViewContentModeScaleToFill;
    _bgImageView.image = bgImage;
    [self addSubview:_bgImageView];
}

- (void)prepareConstraints
{
    WeakSelf;
    
    [_bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf);
    }];
}

- (void)configureBarButtons
{
    WeakSelf;
    
    UIView *firstButton = [self.barButtons firstObject];
    if (firstButton) {
        [self addSubview:firstButton];
        [firstButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.bgImageView).offset(15);
            make.top.equalTo(weakSelf.bgImageView).offset(5);
            make.size.mas_equalTo(ToolBarButtonSize);
        }];
    }
    
    UIView *lastView = firstButton;
    for (int i = 1; i < [self.barButtons count]; i++) {
        UIView *barButton = self.barButtons[i];
        [self addSubview:barButton];
        
        [barButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(lastView.mas_right);
            make.top.equalTo(lastView);
            make.size.mas_equalTo(ToolBarButtonSize);
        }];
        lastView = barButton;
    }
}

#pragma mark - Getters and Setters
- (void)setBarButtons:(NSArray *)barButtons
{
    for (UIView *barButton in _barButtons) {
        [barButton removeFromSuperview];
    }
    
    _barButtons = barButtons;
    
    [self configureBarButtons];
}


@end
